Repository navigation
Conversation
Merging this PR will improve performance by 40.84%
|
| Benchmark | BASE |
HEAD |
Efficiency | |
|---|---|---|---|---|
| ⚡ | test_bench_host_from_connect_args_unix |
26.7 µs | 19 µs | +40.84% |
Tip
Curious why performance improved? Comment @codspeedbot explain why performance improved on this PR, or directly use the CodSpeed MCP with your agent.
Comparing Boulea7:ln-cx/pytest-socket-540-existing-fd (714d55d) with main (1e9ef4f)
miketheman
left a comment
There was a problem hiding this comment.
Thanks for picking up #540, and for the care in these tests. The core idea is right: wrapping a descriptor that already exists doesn't open a new connection, so the guard shouldn't stop it. I'd like a few changes before merging.
CI failure
test_two_consecutive_tests_can_use_an_existing_local_listener fails on every job with Plugin already registered under a different name: socket. pytest-socket is already loaded through its entry point, so pytester.runpytest("-p", "pytest_socket", "-v") (tests/test_socket_fileno.py:267) registers it a second time. pytester.runpytest() is enough. With that change and main merged in, the full suite passes locally.
Unix sockets now get past --allow-unix-socket
The exemption at src/pytest_socket/init.py:135 allows every constructor call that passes a fileno. Some stdlib helpers create brand new sockets in C and only then wrap them that way. On macOS and Linux, with --disable-socket and no --allow-unix-socket, these now succeed where main raises SocketBlockedError:
socket.socketpair()socket.fromfd(fd, socket.AF_UNIX, ...)asyncio.new_event_loop(), whose self-pipe comes fromsocketpair()
Windows still blocks them, since its socketpair() is written in Python and calls socket(AF_INET, ...). So on POSIX only, the PR changes what --allow-unix-socket controls, while the README (lines 22 and 91-95) still presents that flag as the way to allow async event loops.
I'd rather keep the Unix gate on this path:
if (fileno is not None and not _is_unix_socket(family)) or (
_is_unix_socket(family) and allow_unix_socket
):I tried this against your branch: all tests pass, accept() on a TCP listener still works, and socketpair() and new_event_loop() are blocked by default and allowed with allow_unix_socket=True. One gap remains. socket.socket(fileno=fd) without a family arrives with family=-1, so a Unix fd wrapped that way still gets through. That seems acceptable to me, and simpler than inspecting the fd.
Please add a test that socket.socketpair() is blocked without --allow-unix-socket and works with it, so this can't flip again unnoticed.
Tests
- The
_AcceptFdListener._acceptoverride and thefd_cleanupExitStack hand-off (lines 23-66) override CPython's privatesocket._acceptto close an fd that only leaks once the test has already failed. Plainlistener.accept()andsocket.socket(fileno=original.detach())exercise the same behavior. Dropping the scaffolding also removes its copy inside the pytester source at line 223. - In
test_wrapped_fd_respects_host_restrictions_and_closes_on_denial, please call_remove_restrictions()in thefinally. Cleanup works today only becausesocket_allow_hosts()runs afterdisable_socket(), so theconnectpatch lands on the throwawayGuardedSocketclass. In the other order the patch would outlive the test, becauseenable_socket()doesn't restoreconnect. test_wrapping_an_existing_fd_keeps_dns_guardsand the{}case oftest_creating_a_socket_without_an_existing_fd_stays_blockedrepeat coverage that tests/test_dns.py and tests/test_socket.py already have. The{"fileno": None}case is the new part, so keep that one.- Please keep the fd 0 test. It's the only test that fails if the condition regresses to
if fileno:. It doesn't need the hand-builtenv(line 152), though: the script never starts pytest, sosubprocess.run([sys.executable, "-c", script], stdin=subprocess.DEVNULL, timeout=10, check=True)is enough. - Optional, but it would match the report directly: #540 describes a server thread whose
accept()runs while the guard is installed, likesocketserveror the sessionhttpserverfixture in tests/conftest.py. The pytester test installs the guard by hand in a fixture rather than through--disable-socket, so it doesn't go through the plugin's own hooks either.
main has moved since you opened this. #550 added SocketBlockedWarning, a UserWarning subclass, so your pytest.warns(UserWarning, ...) checks still pass, and merging main in applies cleanly.
I worked through this review with Claude Code, which helped reproduce the CI failure and compare the socketpair() and event loop behavior between main and this branch.
Signed-off-by: boulea7 <zln1905391059@163.com>
|
Updated the fd guard to preserve the explicit Unix-family opt-in, with socketpair coverage for the POSIX behavior and Windows TCP fallback. The tests now use normal plugin autoload and ordinary accept/detach calls, clean up host restrictions with Local |
miketheman
left a comment
There was a problem hiding this comment.
Thanks for working through all of that, @Boulea7. Every point from the last round is addressed, and the Windows socketpair() case is a nice addition I didn't ask for.
Approving, with a few small cleanups inline. Each has a suggestion you can add to a batch and commit in one go. Please apply them before we merge. I tried them against this head: the fileno tests pass with no stray warnings, and black, isort and flake8 are clean.
I worked through this review with Claude Code again, which helped check the suggestions against the branch.
| import sys | ||
| import textwrap | ||
| from contextlib import contextmanager | ||
| from pathlib import Path |
There was a problem hiding this comment.
With the cwd= below removed, nothing else uses Path.
| from pathlib import Path |
|
|
||
| import pytest_socket | ||
| from pytest_socket import ( | ||
| SocketBlockedError, |
There was a problem hiding this comment.
For the pytest.warns suggestions on the socketpair() tests below.
| SocketBlockedError, | |
| SocketBlockedError, | |
| SocketBlockedWarning, |
| """) | ||
| subprocess.run( | ||
| [sys.executable, "-c", script], | ||
| cwd=Path(pytest_socket.__file__).resolve().parents[1], |
There was a problem hiding this comment.
The script only imports pytest_socket, which is installed in the environment, so the subprocess doesn't need a working directory.
| cwd=Path(pytest_socket.__file__).resolve().parents[1], |
| with pytest.raises(SocketBlockedError): | ||
| first, second = socket.socketpair() | ||
| with first, second: | ||
| pass |
There was a problem hiding this comment.
The blocked call emits a SocketBlockedWarning that ends up in the suite's warnings summary. Asserting it keeps the output clean. The with first, second: block can't run once socketpair() raises, so it can go.
| with pytest.raises(SocketBlockedError): | |
| first, second = socket.socketpair() | |
| with first, second: | |
| pass | |
| with ( | |
| pytest.raises(SocketBlockedError), | |
| pytest.warns(SocketBlockedWarning), | |
| ): | |
| socket.socketpair() |
| with pytest.raises(SocketBlockedError): | ||
| first, second = socket.socketpair() | ||
| with first, second: | ||
| pass |
There was a problem hiding this comment.
Same change for the Windows variant.
| with pytest.raises(SocketBlockedError): | |
| first, second = socket.socketpair() | |
| with first, second: | |
| pass | |
| with ( | |
| pytest.raises(SocketBlockedError), | |
| pytest.warns(SocketBlockedWarning), | |
| ): | |
| socket.socketpair() |
|
The branch can also use an update from |
Signed-off-by: boulea7 <zln1905391059@163.com>
|
Applied all five inline suggestions and merged |
Allow
socket.socket(fileno=...)to wrap existing Internet socket descriptors while sockets are disabled, so a pre-existing listener can still accept connections. Ordinary Internet socket creation stays blocked, explicit Unix families still require the Unix opt-in, and host restrictions remain active.The tests use normal plugin autoload, ordinary
accept()/detach(), and real--disable-sockethooks across consecutive tests. Main at49db7dais merged, including its fixture teardown changes and current dependencies. The latest review cleanups remove the unused subprocess working directory and assertSocketBlockedWarningalongsideSocketBlockedErrorin both blocked socketpair cases.Fixes #540.
Validation on 2026-10-26 with the current lock on Linux CPython 3.11.2:
49db7dahas 134 passed and the same two failures: the Google TCP connection times out, and localhost resolves an extra127.0.1.1that differs from the expected error string.mypy srcpasses with locked mypy 2.4.0. Plugin statement and branch coverage is 100% on both trees. The default report, which includes tests, decreases from 99.8880% on main to 99.2157% here. The extra uncovered paths are the PR's existing Windows-only test skipped on Linux (five statements) and the descriptor helper's failure-only cleanup (one statement and one branch).The complete mutation gate could not finish: statistics collection stops on the Google test failure. Pre-commit hooks and native Windows/macOS tests have not run locally for this update, and no new performance comparison was collected.
CI for this update has not yet been verified.